import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ability/custom_ui.dart';

/// 验证码状态
enum YJCodeState {
  /// 初始化状态
  none,

  /// 发送验证码成功
  sendCodeSuccess,

  /// 发送验证码失败
  sendCodeFail,
}

class YJCodeButton extends StatefulWidget {
  const YJCodeButton({
    Key? key,
    required this.phoneNo,
    this.isTextButton = false,
    this.enableBgColor,
    this.disableBgColor,
    this.yjCodeState = YJCodeState.none,
    required this.sendCodeCallBack,
    this.failCallback,
    this.enableTextColor,
    this.disableTextColor,
    this.speed = 60,
  }) : super(key: key);

  /// 手机号
  final String phoneNo;

  /// 是否按钮文本/文字文本
  final bool? isTextButton;

  /// 背景颜色
  final Color? enableBgColor;

  /// 禁用状态背景颜色
  final Color? disableBgColor;

  /// 文字颜色
  final Color? enableTextColor;

  /// 禁用文字颜色
  final Color? disableTextColor;

  /// 验证码状态
  final YJCodeState? yjCodeState;

  /// 点击发送验证码回调
  final Function sendCodeCallBack;

  /// 失败返回
  final void Function(Object o)? failCallback;

  /// 总倒计时时长 单位：秒
  final int speed;

  @override
  State<StatefulWidget> createState() => _YJCodeButtonState();
}

class _YJCodeButtonState extends State<YJCodeButton> {
  /// 开始倒计时 时间
  int? _startTime;

  /// 当前倒计时 时间
  int _countDownTime = 0;

  /// 时间控件
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    print("YJCodeButton initState");
  }

  @override
  void didUpdateWidget(covariant YJCodeButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("YJCodeButton didUpdateWidget ${widget.yjCodeState}");
    _updateCodeWidget();
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer?.cancel();
      _timer = null;
    }
  }

  void _updateCodeWidget() {
    /// 正在倒计时
    if (_countDownTime > 0) {
      print("YJCodeButton 正在倒计时");
      return;
    }

    /// 验证码状态
    if (widget.yjCodeState == YJCodeState.none) {
      print("YJCodeButton 验证码状态 none");
      return;
    } else if (widget.yjCodeState == YJCodeState.sendCodeSuccess) {
      print("YJCodeButton 验证码状态 sendCodeSuccess");
      _startTime = getTime();
      _countDownTime = widget.speed;
      _countDown();
    } else if (widget.yjCodeState == YJCodeState.sendCodeFail) {
      print("YJCodeButton 验证码状态 sendCodeFail");
      return;
    }
  }

  void _sendCode() {
    print("YJCodeButton _sendCode ");

    /// 正在倒计时
    if (_countDownTime > 0) {
      print("YJCodeButton _countDownTime > 0");
      return;
    }

    /// 点击获取验证码
    bool phoneVerify = widget.phoneNo.isPhone;
    if (phoneVerify) {
      widget.sendCodeCallBack();
      print("YJCodeButton 点击获取验证码");
      return;
    }
    print("YJCodeButton 手机号校验失败");
    if (widget.failCallback != null) {
      widget.failCallback!({
        "message": '手机号校验失败',
        "offstage": false,
      });
    }
  }

  /// 倒计时
  void _countDown() {
    var time = _startTime != null ? _startTime : 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      int nowTime = getTime();
      int result = widget.speed - (nowTime - time!);
      if (result < 0) {
        _timer?.cancel();
      }
      _countDownTime = result;
      setState(() {});
    });
  }

  int getTime() {
    return (DateTime.now().millisecondsSinceEpoch / 1000).round();
  }

  bool isDownTime() {
    return (_startTime == null || _countDownTime <= 0);
  }

  String getCodeName() {
    var timeText = "获取验证码";
    if (_startTime == null) {
      timeText = "获取验证码";
    } else if (_startTime != null && _countDownTime <= 0) {
      timeText = "获取验证码";
    } else if (_startTime != null && _countDownTime < 10) {
      timeText = "重新发送(0${_countDownTime})";
    } else if (_startTime != null && _countDownTime >= 10) {
      timeText = "重新发送(${_countDownTime})";
    }
    return timeText;
  }

  @override
  Widget build(BuildContext context) {
    String timeText = getCodeName();
    Color? bgColor = Colors.transparent;
    Color? textColor = Colors.white;
    if (widget.isTextButton == true) {
      bgColor = isDownTime()
          ? widget.enableBgColor ?? YJColors.THEME_COLOR
          : widget.disableBgColor ?? Color(0xFFFFEBDD);
      textColor = isDownTime()
          ? widget.enableTextColor ?? YJColors.WHITE
          : widget.disableTextColor ?? YJColors.THEME_COLOR;
    } else {
      textColor = isDownTime()
          ? widget.enableTextColor ?? YJColors.THEME_COLOR
          : widget.disableTextColor ?? Color(0xa6FF6A00);
    }
    return Container(
      width: YJSize.dp(102),
      height: YJSize.dp(32),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(50)),
        color: bgColor,
      ),
      alignment: Alignment.center,
      child: InkWell(
        onTap: () {
          _sendCode();
        },
        child:
            TextView.text(timeText, fontSize: YJSize.sp(14), color: textColor),
      ),
    );
  }
}
